package edu.sandau.app.basic.service.impl;

import edu.sandau.app.basic.domain.Order;
import edu.sandau.app.basic.domain.OrderDetail;
import edu.sandau.app.basic.domain.OrderExample;
import edu.sandau.app.basic.mapper.OrderMapper;
import edu.sandau.app.basic.service.OrderDetailService;
import edu.sandau.app.basic.service.OrderService;
import edu.sandau.app.basic.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderDetailService orderDetailService;
    
    @Autowired
    private DishService dishService;
    
    @Override
    public List<Order> getAllOrders() {
        OrderExample example = new OrderExample();
        example.setOrderByClause("create_time DESC");
        return orderMapper.selectByExample(example);
    }
    
    @Override
    public Order getOrderById(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }
    
    @Override
    @Transactional
    public int createOrder(Order order) {
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        if (order.getOrderStatus() == null) {
            order.setOrderStatus("0"); // 默认状态为待支付
        }
        if (order.getOrderNo() == null || order.getOrderNo().trim().isEmpty()) {
            order.setOrderNo(generateOrderNo()); // 生成订单号
        }
        return orderMapper.insertSelective(order);
    }
    
    @Override
    @Transactional
    public int updateOrder(Order order) {
        order.setUpdateTime(new Date());
        return orderMapper.updateByPrimaryKeySelective(order);
    }
    
    @Override
    @Transactional
    public int deleteOrder(Long id) {
        return orderMapper.deleteByPrimaryKey(id);
    }
    
    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        OrderExample example = new OrderExample();
        example.createCriteria().andUserIdEqualTo(userId);
        example.setOrderByClause("create_time DESC");
        return orderMapper.selectByExample(example);
    }
    
    @Override
    public Order getOrderByOrderNo(String orderNo) {
        OrderExample example = new OrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<Order> orders = orderMapper.selectByExample(example);
        return orders.isEmpty() ? null : orders.get(0);
    }
    
    @Override
    public List<Order> getOrdersByStatus(String status) {
        OrderExample example = new OrderExample();
        example.createCriteria().andOrderStatusEqualTo(status);
        example.setOrderByClause("create_time DESC");
        return orderMapper.selectByExample(example);
    }
    
    @Override
    @Transactional
    public int cancelOrder(Long id) {
        Order order = new Order();
        order.setOrderId(id);
        order.setOrderStatus("3"); // 已取消
        order.setUpdateTime(new Date());
        return orderMapper.updateByPrimaryKeySelective(order);
    }
    
    @Override
    @Transactional
    public int payOrder(Long id, String paymentMethod) {
        // 更新订单状态为已支付
        Order order = new Order();
        order.setOrderId(id);
        order.setOrderStatus("1"); // 已支付
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());
        
        int result = orderMapper.updateByPrimaryKeySelective(order);
        
        // 如果支付成功，更新菜品销量
        if (result > 0) {
            updateDishSalesCount(id);
        }
        
        return result;
    }
    
    /**
     * 更新菜品销量
     * 根据订单ID获取订单详情，然后更新每个菜品的销量
     */
    @Transactional
    private void updateDishSalesCount(Long orderId) {
        try {
            // 获取订单详情
            List<OrderDetail> orderDetails = orderDetailService.getOrderDetailsByOrderId(orderId);
            
            // 遍历订单详情，更新每个菜品的销量
            for (OrderDetail detail : orderDetails) {
                if (detail.getDishId() != null && detail.getQuantity() != null) {
                    dishService.increaseSalesCount(detail.getDishId(), detail.getQuantity());
                }
            }
        } catch (Exception e) {
            // 记录错误日志，但不影响支付流程
            System.err.println("更新菜品销量失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    @Override
    public String generateOrderNo() {
        return "ORD" + System.currentTimeMillis();
    }
}
